#include "WVTree.h"
#include "XTimer.h"
#include "WVFile.h"

inline bool Find(const WVFile& file, const WVector& point, float threshold, WVector& result)
{
	const std::vector<WVector>& points = file.GetVectors();

	float similar = points[0].CalcSimilar(point);
	size_t index = 0;
	for (size_t i = 1; i < points.size(); ++i)
	{
		float s = points[i].CalcSimilar(point);
		if (similar < s)
		{
			similar = s;
			index = i;
		}
	}

	if (similar > threshold)
	{
		result = points[index];
		return true;
	}

	return false;
}

int main(int argc, char** argv)
{
	WVFile trainFile(220000);
	trainFile.Read("../djdq.txt");
	
	// Build Tree
	const size_t MAX_LEVELS = 12;
	const float MARGIN = 0.05f;
	WVTree tree(MAX_LEVELS, MARGIN);	
	tree.SetVectors(trainFile.GetVectors());
	tree.Report();

	WVFile testFile(100);
	testFile.Read("../test.txt"); 
	const std::vector<WVector>& tests = testFile.GetVectors();

	float threshold = 0.25f;
	WVector result;

	XTimer timer;
	for (int i = 0; i < testFile.GetNumWords(); ++i)
	{
		if (tree.Find(tests[i], threshold, result))
		{
			printf("kdtree, %d, %s -> %s\n", i, tests[i].GetWord().c_str(), result.GetWord().c_str());
		}
	}
	float time1 = timer.GetMilliseconds(true);

	for (int i = 0; i < testFile.GetNumWords(); ++i)
	{
		if (Find(trainFile, tests[i], threshold, result))
		{
			printf("search, %d, %s -> %s\n", i, tests[i].GetWord().c_str(), result.GetWord().c_str());
		}
	}
	float time2 = timer.GetMilliseconds(true);

	printf("kdtree, time1 = %.3f\n", time1);
	printf("search, time2 = %.3f\n", time2);

	return 0;
}
